package com.example.musicplayer.commonUtils;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

public class Timer {
    public static final int UPDATE = 1;
    private boolean mPause;
    private int mTimeCounts;
    private int mInterval;
    private TimerListener mTimerListener;
    private TimerHandler mTimerHandler;

    @SuppressLint("HandlerLeak")
    private class TimerHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == UPDATE) {
                if (mTimerListener != null) {
                    mTimerListener.update();
                } else {
                    mTimerHandler = null;
                }
            }
        }
    }

    public Timer(int interval, TimerListener timerListener) {
        mTimeCounts = 0;
        mPause = false;
        setInterval(interval);
        setTimerListener(timerListener);
    }

    public void setInterval(int interval) {
        if (interval <= 0) {
            interval = 1;
        }
        mInterval = interval;
    }

    public int getInterval() {
        return mInterval;
    }

    public void setTimerListener(TimerListener timerListener) {
        mTimerListener = timerListener;
        if (mTimerListener != null) {
            mTimerHandler = new TimerHandler();
        }
    }

    public TimerListener getTimerListener() {
        return mTimerListener;
    }

    public Handler getHandler() {
        return mTimerHandler;
    }

    public boolean update(int timeCounts) {
        if (mPause) {
            return false;
        }
        mTimeCounts += timeCounts;
        if (mTimeCounts >= mInterval) {
            mTimeCounts = 0;
            return true;
        } else {
            return false;
        }
    }

    public void start() {
        mTimeCounts = 0;
        resume();
    }

    public void resume() {
        mPause = false;
    }

    public void pause() {
        mPause = true;
    }

    public interface TimerListener {
        void update();
    }
}